﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Media;
using LiveCharts;
using LiveCharts.Wpf;
using LiveCharts.Defaults;

namespace UI_Scripts2
{
    public partial class UCinbox_account : UserControl
    {
        private Api api;
        DateTime today = DateTime.Now;  //当前日期
        int daysAmount;                 //用户要求显示的天数
        List<UserBills> userBills;      //给定天数内的所有账目
        public string currentCate = ""; //当前添加记账的类型

        //用于折线图的数据
        string[] xlabels;          //折线图的x坐标
        Dictionary<int, double> dailyExpend = new Dictionary<int, double>(0);  //每天的收支总数
        Dictionary<int, double> dailyRevenue = new Dictionary<int, double>(0);
        double[] expendAmount, revenueAmount;

        //用于饼图的数据
        string[] expendCates = new string[] { "dining", "transport", "daily", "entertainment", "medicine", "clothing" }; //默认开销类型
        string[] revenueCates = new string[] { "salaries", "living_costs", "gifts", "investment" };//默认收入类型
        Dictionary<string, double> cateExpend = new Dictionary<string, double>(0);
        Dictionary<string, double> cateRevenue = new Dictionary<string, double>(0); //每个分类下的收支总数

        public int AccountID;

        public UCinbox_account() //带token的构造函数
        {
            InitializeComponent();
            AccountTable.AutoScroll = true;
            AddingPanel.Visible = false;
            //ExpendCateGroup.Visible = false;
            RevenueCateGroup.Visible = false;

            api = new Api();
 
            daysAmount = (int)DaysAmount.Value; //用户要求显示的天数
            userBills = api.GetUserBillsAsync(Api.Token, daysAmount); //给定天数内的所有账目

            CartesianShow();
            PieChartShow();
            AccountsShow();
        }

        private void AddAccountButton_Click(object sender, EventArgs e) //开始添加一条记账
        {
            if (AddAccountButton.Text == "+")
            {
                groupBox1.Visible = false;
                showBills.Visible = false;
                AddingPanel.Visible = true;
                DateTimePicker.Value = DateTime.Now;
                AddingPanel.Location = new Point(-337, 15);

                AddButton.Text = "ADD";
                ExpendChosen.Checked = true;
                RemarkTextBox.Clear();
                AmountTextBox.Clear();

                timer1.Start();
            }
            else
            {
                timer1.Start();
            }
        }

        private int loc_x = -337;
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (AddAccountButton.Text == "+")
            {
                if (loc_x < 4)
                {
                    loc_x += 30;
                    AddingPanel.Location = new Point(loc_x, 15);
                    AddAccountButton.Location = new Point(loc_x + 337, 568);
                }
                else
                {
                    AddAccountButton.Text = "×";
                    timer1.Stop();
                    AccountTable.Visible = false;
                    AccountTable.Enabled = false;
                    return;
                }
            }
            else
            {
                if (loc_x > -337)
                {
                    loc_x -= 30;
                    AddingPanel.Location = new Point(loc_x, 15);
                    AddAccountButton.Location = new Point(loc_x + 337, 568);
                }
                else
                {
                    AddAccountButton.Text = "+";
                    timer1.Stop();
                    AddingPanel.Visible = false;
                    AccountTable.Visible = true;
                    AccountTable.Enabled = true;
                    groupBox1.Visible = true;
                    showBills.Visible = true;
                    return;
                }
            }
        }

        //为currentCate赋值
        private void Dining_CheckedChanged(object sender, EventArgs e)
        {
            if (Dining.Checked)
                currentCate = "dining";
        }
        private void Transport_CheckedChanged(object sender, EventArgs e)
        {
            if (Transport.Checked)
                currentCate = "transport";
        }
        private void Daily_CheckedChanged(object sender, EventArgs e)
        {
            if (Daily.Checked)
                currentCate = "daily";
        }
        private void Entertainment_CheckedChanged(object sender, EventArgs e)
        {
            if (Entertainment.Checked)
                currentCate = "entertainment";
        }
        private void Medicine_CheckedChanged(object sender, EventArgs e)
        {
            if (Medicine.Checked)
                currentCate = "medicine";
        }
        private void Clothing_CheckedChanged(object sender, EventArgs e)
        {
            if (Clothing.Checked)
                currentCate = "clothing";
        }

        private void Salaries_CheckedChanged(object sender, EventArgs e)
        {
            if (Salaries.Checked)
                currentCate = "salaries";
        }
        private void Living_CheckedChanged(object sender, EventArgs e)
        {
            if (Living.Checked)
                currentCate = "living_costs";
        }
        private void Gifts_CheckedChanged(object sender, EventArgs e)
        {
            if (Gifts.Checked)
                currentCate = "gifts";
        }
        private void Investment_CheckedChanged(object sender, EventArgs e)
        {
            if (Investment.Checked)
                currentCate = "investment";
        }

        private void AddButton_Click(object sender, EventArgs e) //确认添加或更新记录
        {
            bool type = (ExpendChosen.Checked) ? true : false;
            float amount = float.Parse(AmountTextBox.Text);
            string remark = RemarkTextBox.Text;
            DateTime date = DateTimePicker.Value;
            
            PostBill postBill = new PostBill(currentCate, type, amount, remark, date, Api.Token);
            //MessageBox.Show("type: "+type+"\namount: "+amount + "\nremark: " + remark + "\ndate: " + date + "\ntoken: " + token);

            //调用api
            if (AddButton.Text == "ADD")
            {
                string state = api.PostUserBillsAsync(postBill);
                if (state == "Created")
                {
                    timer1.Start();
                    MessageBox.Show("Post succeed");
                    ExpendChosen.Checked = true;
                    RemarkTextBox.Clear();
                    AmountTextBox.Clear();
                    userBills = api.GetUserBillsAsync(Api.Token, daysAmount); //给定天数内的所有账目
                    CartesianShow();
                    PieChartShow();
                    AccountsShow();
                }
                else
                    MessageBox.Show(state);
            }
            else if (AddButton.Text == "UPDATE")
            {
                string state = api.PutUserBillsAsync(Api.Token,AccountID, postBill);
                if (state == "OK")
                {
                    timer1.Start();
                    MessageBox.Show("Update succeed");
                    ExpendChosen.Checked = true;
                    RemarkTextBox.Clear();
                    AmountTextBox.Clear();
                    AddButton.Text = "ADD";
                    userBills = api.GetUserBillsAsync(Api.Token, daysAmount); //给定天数内的所有账目
                    CartesianShow();
                    PieChartShow();
                    AccountsShow();
                }
                else
                    MessageBox.Show(state);
            }
        }

        private void showBills_Click(object sender, EventArgs e)  //更新显示的天数
        {
            daysAmount = (int)DaysAmount.Value; //用户要求显示的天数
            userBills = api.GetUserBillsAsync(Api.Token, daysAmount); //给定天数内的所有账目

            //再次调用饼图、折线图、流水显示函数
            CartesianShow();
            PieChartShow();
            AccountsShow();
        }

        public void CartesianShow() //显示折线图
        {
            userBills = api.GetUserBillsAsync(Api.Token, daysAmount);
            xlabels = new string[daysAmount];  //折线图横坐标

            dailyExpend = new Dictionary<int, double>(0);  //每天的收支总数
            dailyRevenue = new Dictionary<int, double>(0);

            expendAmount = new double[daysAmount]; //相应折线图的取值
            revenueAmount = new double[daysAmount];

            //userBills = api.GetUserBillsAsync(Api.Token, daysAmount);
            //为折线图横坐标赋值
            for(int day = 0; day < daysAmount;day++)
            { 
                System.TimeSpan duration = TimeSpan.Parse(-day+".00:00:00");
                System.DateTime answer = today.Date.Add(duration);
                xlabels[daysAmount - day - 1] = answer.Day.ToString();
            }
            //初始化dailyExpend和dailyRevenue
            foreach (var userBill in userBills)
            {
                dailyExpend[userBill.Date.Day] = 0;
                dailyRevenue[userBill.Date.Day] = 0;
            }

            //为dailyExpend和dailyRevenue赋值
            foreach (var userBill in userBills)
            {
                if (userBill.Type)
                    dailyExpend[userBill.Date.Day] += userBill.Amount;
                else
                    dailyRevenue[userBill.Date.Day] += userBill.Amount;
            }

            int index = 0;
            //为expendAmount和revenueAmount赋值
            foreach (var i in dailyExpend)
            {
                expendAmount[daysAmount - index - 1] = i.Value; index++;
            }
            index = 0;
            foreach (var i in dailyRevenue)
            {
                revenueAmount[daysAmount - index - 1] = i.Value; index++;
            }

            cartesianChart1.AxisX.Clear();
            cartesianChart1.AxisY.Clear();
            cartesianChart1.AxisX.Add(new Axis
            {
                Title = "Days",
                Labels = xlabels
            });
            cartesianChart1.AxisY.Add(new Axis
            {
                Title = "Amounts",
                LabelFormatter = value => value.ToString("C")
            });
            cartesianChart1.LegendLocation = LegendLocation.Bottom;
            cartesianChart1.Series = new SeriesCollection   //支出与收入曲线放在同一折线图中
            {
                //支出
                new LineSeries
                {
                    Title = "Expenditure",
                    Values = new ChartValues<double>(expendAmount),
                    LineSmoothness = 0,
                    PointGeometrySize = 10
                },
                //收入
                new LineSeries
                {
                    Title = "Revenue",
                    Values = new ChartValues<double>(revenueAmount),
                    LineSmoothness = 0,
                    PointGeometrySize = 10
                }
            };
        }
        public void PieChartShow()  //显示饼图
        {
            cateExpend[""] = 0;
            cateRevenue[""] = 0;
            userBills = api.GetUserBillsAsync(Api.Token, daysAmount);
            //初始化cateExpend、cateRevenue
            foreach (var i in expendCates)
            {
                cateExpend[i] = 0;
            }
            foreach (var i in revenueCates)
            {
                cateRevenue[i] = 0;
            }

            //string s = "";
            //foreach (var userBill in userBills)
            //{
            //    s += userBill.Category+"\n";
            //}
            //MessageBox.Show(s);

            //为cateExpend、cateRevenue赋值，并将自定义收支类型添加到收支类型数组中
            foreach (var userBill in userBills)
            {
                if (userBill.Type)
                    cateExpend[userBill.Category] += userBill.Amount;
                else
                    cateRevenue[userBill.Category] += userBill.Amount;
            }

            //Func<ChartPoint, string> PointLabel = chartPoint => string.Format("{0} ({1:P})", chartPoint.Y, chartPoint.Participation);

            //支出饼图
            pieChart1.Series.Clear();
            foreach (var cate in expendCates)
            {
                Func<ChartPoint, string> PointLabel = chartPoint => string.Format("{0} ({1:P})", cate, chartPoint.Participation);
                pieChart1.Series.Add(new PieSeries
                {
                    Title = cate,
                    Values = new ChartValues<double> { cateExpend[cate] },
                    DataLabels = false,
                    LabelPoint = PointLabel
                });
            }

            //收入饼图
            pieChart2.Series.Clear();
            foreach (var cate in revenueCates)
            {
                Func<ChartPoint, string> PointLabel = chartPoint => string.Format("{0} ({1:P})", cate, chartPoint.Participation);
                pieChart2.Series.Add(new PieSeries
                {
                    Title = cate,
                    Values = new ChartValues<double> { cateRevenue[cate] },
                    DataLabels = false,
                    LabelPoint = PointLabel
                });
            }

            var sum_exp = 0;
            var sum_inc = 0;
            foreach(var b in userBills)
            {
                if (b.Type == true)
                {
                    sum_exp += b.Amount;
                }
                else
                {
                    sum_inc += b.Amount;
                }
            }
            this.SumExpense.Text = sum_exp.ToString();
            this.SumIncome.Text = sum_inc.ToString();        
        }
        public void AccountsShow() //显示记账流水
        {
            userBills = api.GetUserBillsAsync(Api.Token, daysAmount);
            AccountTable.Controls.Clear();
            foreach (var userBill in userBills)
            {
                AccountCell accountCell = new AccountCell();

                accountCell.AccountID = userBill.Id;
                accountCell.type = userBill.Type;
                //accountCell.token = Api.Token;
                accountCell.category.Text = userBill.Category;
                accountCell.PriceLabel.Text = userBill.Amount.ToString();
                if (userBill.Type)
                    accountCell.typeLabel.Text = "-";
                else
                    accountCell.typeLabel.Text = "+";
                accountCell.RemarkLabel.Text = userBill.Remark;
                accountCell.DateLabel.Text = userBill.Date.ToString();

                AccountTable.Controls.Add(accountCell); //加入到AccountTable中
                accountCell.Dock = DockStyle.Top;
            }
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void guna2HtmlLabel1_Click(object sender, EventArgs e)
        {

        }

        private void CloseButton_Click(object sender, EventArgs e)
        {
            MainPage mainPage = (MainPage)CloseButton.Parent.Parent.Parent;
            mainPage.timer1.Start();
        }

        private void ExpendChosen_CheckedChanged(object sender, EventArgs e)
        {
            if (ExpendChosen.Checked)
            {
                CategoryPanel.Controls.Add(ExpendCateGroup);
                ExpendCateGroup.Visible = true;
                RevenueCateGroup.Visible = false;
                ExpendCateGroup.Location = new Point(18, 17);
            }
            else if(RevChosen.Checked)
            {
                CategoryPanel.Controls.Add(RevenueCateGroup);
                RevenueCateGroup.Visible = true;
                ExpendCateGroup.Visible = false;
                RevenueCateGroup.Location = new Point(18, 17);
            }
        }
    }
}
